const Koa = require('koa');
const app = new Koa();
const json = require('koa-json');
const onerror = require('koa-onerror');
const staticServer = require('koa-static-server');
const bodyparser = require('koa-body');
const path = require('path');
const logger = require('koa-logger');
const config = require("./config");
const networkInterfaces = require('os').networkInterfaces(); //获取网卡信息

// 客户端异常响应
onerror(app);

// post请求参数解析与上传
app.use(bodyparser({
  jsonLimit: '10mb',
  multipart: true,
  formidable: {
    maxFileSize: 2000 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  },
  onerror: function (err, ctx) {
    ctx.throw('body parse error', 422);
  }
}));
// 自动解析对象返回客户端为json
app.use(json());
// 开发中显示日志
app.use(logger());
//静态文件服务
app.use(staticServer({ rootDir: path.join(__dirname, 'www', 'static'), rootPath: '/static' }));

// 控制台 请求输出
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// 控制台 异常输出
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

app.use(require('./routes'));
app.listen(config.port, () => {
  const ens = Object.keys(networkInterfaces)[0];
  const address = networkInterfaces[ens][1].address || networkInterfaces[ens][0].address; // 获取内网ip
  const notice = `open:
        http://localhost:${config.port},
        http://${address}:${config.port}
      `
  console.log(notice);
});